package util;

import com.adventnet.snmp.beans.SnmpTable;
import com.adventnet.snmp.beans.SnmpTableEvent;
import com.adventnet.snmp.beans.SnmpTableListener;
import com.adventnet.snmp.beans.SnmpTarget;

public class TableListener implements SnmpTableListener {
	
	/**
	 * get ipRouteTable (MIB IP-21)
	 * 
	 * @param dottedNetAddress
	 * @throws Exception
	 */
	public void getIpRouteTable(String dottedNetAddress)
			throws Exception {
		SnmpTable table = new SnmpTable();
		table.setTableOID(dottedNetAddress);
		
		// To load MIBs from compiled file
		table.setLoadFromCompiledMibs(true);
		table.loadMibs(LIB_MIB + _RFC1213);

		// instantiate this class to receive table events, and register it
		TableListener tl = new TableListener();
		table.addSnmpTableListener(tl);
		table.setTableOID("ipRouteTable");
	}

	/**
	 * This is the listener method which is notified of table changes
	 */
	public void tableChanged(SnmpTableEvent e) {
		SnmpTable table = (SnmpTable) e.getSource();
		/* necessary check */
		if (e.isEndOfTable() || e.getType() == 2) {
			if (table.getRowCount() == 0) // no rows and we're being notified
				System.err.println(table.getErrorString());
			return;
		}
		
		/* print */
		StringBuffer sb = new StringBuffer();

		if (e.getFirstRow() == 0) { // we're being notified of first row
			for (int i = 0; i < table.getColumnCount(); i++)
				// print column names
				sb.append(table.getColumnName(i) + " \t");
			System.out.println(sb.toString());
		}

		// print the rows we're getting
		sb = new StringBuffer();
		for (int j = e.getFirstRow(); j <= e.getLastRow(); j++) {
			for (int i = 0; i < table.getColumnCount(); i++)
				sb.append(table.getValueAt(j, i) + " \t");
		}
		System.out.println(sb.toString());
	}
	
	private static String LIB_MIB = "D:/SNMPAPI/mibs/";
	private static String _RFC1213 = "RFC1213-MIB";
}
